<template>
	<view v-if="!isLogin">
		<sfulogin :title=showtitle @loginEvent="login"></sfulogin>
	</view>
	<view v-else>
			<view>
				<view class="btns">
				<u-button class="ubtn" @click="onPublishBtnClick">发布</u-button>
				</view>
				<view id="localVideoDiv"></view>
				<p>远端视频</p>
				<view id="remoteVideoDiv"></view>
				   
			</view>
	</view>
	
</template>

<script>
	import sfulogin from '@/components/sfulogin/sfulogin.vue'
	import SFU from '@/common/SFU.js';
	import Player from '@/common/Player.js';
	export default {
		data() {
			return {
				showtitle:"sfu音视频demo go",
				users:[],
				sfu:'',
				connected:false,
				published : false,
				players:new Map(),
				isLogin:false,
				userName:'',
				roomId:'',
				userId:this.getRandomUserId(),
			}
		},
		components:{
			sfulogin
		},
		methods: {
			onPublishBtnClick(){
			    if(!this.connected){
			        console.log('客户端还没有连接到服务器...');
			        return;
			    }
			    if(this.published){
			        console.log('已经发布了音视频...');
			        return;
			    }
			    console.log('开始发布音视频...');
			    this.sfu.publish();
			   this.published = true;
			},
			login(userName,roomId){
				this.sfu = new SFU(this.userId,roomId);
				uni.$on('connect',() =>{
				    console.log('Connected to SFU!');
				    this.connected = true;
					this.isLogin = true;
					this.userName = userName;
					this.roomId = roomId;
				    
				    this.sfu.join(this.userId,this.userName,this.roomId);
				
				});
				
				uni.$on('disconnect',() => {
				    this.connected = false;
				});
				
				uni.$on('addLocalStream',(id,stream) => {
				    var player = new Player({id,stream,parent:'localVideoDiv'});
				    this.players.set(id,player);
				});
				
				uni.$on('addRemoteStream',(id,stream) => {
				    var player = new Player({id,stream,parent:'remoteVideoDiv'});
				    this.players.set(id,player);
				});
				
				uni.$on('removeRemoteStream',(id,stream) => {
				    var player = this.players.get(id);
				    if(player){
				        player.destory();
				    }
				});
			},
			getRandomUserId() {
			    var num = "";
			    for (var i = 0; i < 6; i++) {
			        num += Math.floor(Math.random() * 10);
			    }
			    return num;
			},
		}
	}
</script>

<style lang="scss">
.btns {
		margin-top: 20upx;
		text-align: center;
	
		.ubtn {
			display: inline-block;
			margin: 0 20upx;
		}
	}
</style>
